<template>
  <div class="dropzone" @drop="drop($event)" @dragover="dragOver($event)">
    <h2>Languages</h2>
    <TransitionGroup name="list">
      <div
        v-for="(item, index) in languages"
        :key="item.name"
        class="draggable"
        draggable="true"
        @dragstart="dragStart(index)"
        @dragenter="dragEnter(index)"
        @dragleave="dragLeave()"
      >
        {{ item.name }}
      </div>
    </TransitionGroup>
  </div>
</template>

<script setup lang="ts">
import { reactive } from 'vue';

interface Language {
  name: string;
}

const languages = reactive<Language[]>([
  {
    name: 'typescript',
  },
  {
    name: 'javascript',
  },
  {
    name: 'C++',
  },
  {
    name: 'java',
  },
  {
    name: 'rust',
  },
  {
    name: 'golang',
  },
]);

const record = reactive({
  current: -1,
  replace: -1,
});

// 排序方式
const reorder = (languages: Language[], current: number, replace: number) => {
  if (current === -1 || replace === -1) {
    return;
  }
  const [removedLanguage] = languages.splice(current, 1);
  console.log('removedLanguage :>> ', removedLanguage);
  languages.splice(replace, 0, removedLanguage);
};

const dragStart = (index: number) => {
  record.current = index;
};

const dragEnter = async (index: number) => {
  reorder(languages, record.current, record.replace);
  await nextTick();
  record.replace = index;
};

const dragLeave = () => {
  record.replace = -1;
};

// drop 事件在元素或选中的文本被放置在有效的放置目标上时被触发
const drop = (event: DragEvent) => {
  event.preventDefault();
};
// 当元素或者选择的文本被拖拽到一个有效的放置目标上时，触发 dragover 事件（每几百毫秒触发一次）
const dragOver = (event: DragEvent) => {
  event.preventDefault();
};
</script>

<style scoped>
.draggable {
  @apply bg-white my-3 p-3 text-center text-black dark:text-white dark:bg-black;
}

.dropzone {
  @apply bg-green-600 p-3 m-2 w-96;
}
.list-move, /* 对移动中的元素应用的过渡 */
    .list-enter-active,
    .list-leave-active {
  transition: all 0.2s ease;
}
</style>
